//
//  RegisterViewController.m
//  F50
//
//  Created by 郝 巍 on 15/5/6.
//  Copyright (c) 2015年 ZACK. All rights reserved.
//

#import "RegisterViewController.h"
#import "UserInfoViewController.h"
#import "ResetWordViewController.h"
@interface RegisterViewController ()<UITextFieldDelegate>
{
    UIButton *codeBtn;
    NSTimer *time;
    int count;
}
@end

@implementation RegisterViewController

- (void)createBackground
{
    self.navigationController.navigationBarHidden = YES;
    UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    bgView.image = [UIImage imageNamed:@"background"];
    bgView.userInteractionEnabled = YES;
    [self.view addSubview:bgView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(20, 32, 15, 18);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:backBtn];
    
    
    
    
    //中间标题
    UILabel *  nav_title=[[UILabel alloc] initWithFrame:CGRectMake(WIDTH/2 - 80, 20, 160, 40)];
    nav_title.text = self.titleStr;
    nav_title.textAlignment = NSTextAlignmentCenter;
    nav_title.font=[UIFont boldSystemFontOfSize:20];
    nav_title.textColor=[UIColor whiteColor];
    nav_title.backgroundColor=[UIColor clearColor];
    [bgView addSubview:nav_title];

    
    self.phoneNum = [[UITextField alloc]initWithFrame:CGRectMake(15, 75, WIDTH - 30, 40)];
    self.phoneNum.placeholder = @"请输入手机号码";
    self.phoneNum.delegate = self;
    self.phoneNum.textAlignment = NSTextAlignmentCenter;
    self.phoneNum.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneNum.backgroundColor = [UIColor whiteColor];
    self.phoneNum.layer.cornerRadius = 5;
    [bgView addSubview:self.phoneNum];
    
    self.code = [[UITextField alloc]initWithFrame:CGRectMake(15, 130, WIDTH/2 - 30, 40)];
    self.code.placeholder = @"请填写验证吗";
    self.code.delegate = self;
    self.code.textAlignment = NSTextAlignmentCenter;
    self.code.keyboardType = UIKeyboardTypeNumberPad;
    self.code.backgroundColor = [UIColor whiteColor];
    self.code.layer.cornerRadius = 5;
    [bgView addSubview:self.code];
    
    codeBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(WIDTH/2, 130, WIDTH/2 - 15, 42);
    [codeBtn addTarget:self action:@selector(getCodeNum) forControlEvents:UIControlEventTouchUpInside];
    [codeBtn setBackgroundImage:[UIImage imageNamed:@"getcode"] forState:UIControlStateNormal];
    [codeBtn setTitle:@"点击获取验证码" forState:UIControlStateNormal];
    codeBtn.layer.cornerRadius = 5;
    [codeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bgView addSubview:codeBtn];
  
    
    
    UIButton *doReg = [UIButton buttonWithType:UIButtonTypeCustom];
    doReg.frame = CGRectMake(15, 185, WIDTH - 30, 40);
    [doReg addTarget:self action:@selector(doRegister) forControlEvents:UIControlEventTouchUpInside];
//    [login setBackgroundColor:RGB(63, 109, 196)];
    [doReg setBackgroundImage:[UIImage imageNamed:@"register"] forState:UIControlStateNormal];
    [doReg setTitle:@"下一步" forState:UIControlStateNormal];
    doReg.layer.cornerRadius = 8;
    [doReg setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bgView addSubview:doReg];
    
    
  
    
    
//    UILabel *wordLab = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2 - 150, 235, 300, 20)];
//    wordLab.text = @"点击上面的“登录”按钮，即表示你同意";
//    wordLab.textAlignment = NSTextAlignmentCenter;
//    wordLab.font = [UIFont systemFontOfSize:13];
//    wordLab.textColor = RGB(158, 158, 158);
//    [bgView addSubview:wordLab];
//    
//    
//    
//    UIButton *dealBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    dealBtn.frame = CGRectMake(15, 260, WIDTH - 30, 20);
//    [dealBtn addTarget:self action:@selector(readDeal) forControlEvents:UIControlEventTouchUpInside];
//    [dealBtn setTitle:@"《F50season5服务协议》" forState:UIControlStateNormal];
//    [dealBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    dealBtn.titleLabel.font = [UIFont systemFontOfSize:13];
//    [bgView addSubview:dealBtn];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self createBackground];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)getCodeNum{
    
    // 先判断是否有输入
    if (self.phoneNum.text.length == 0) {
        // 是否需要提醒？
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请输入手机号"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles: nil];
        [alert show];
        return;
    }
    NSString *regex = @"^((13)|(14)|(15)|(18))\\d{9}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:self.phoneNum.text];
    
    if (!isMatch) {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请输入正确的手机号码"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
        
        [alert show];
        
        
        return;
        
    }
    
    
    
    
    count = 0;
    time = [NSTimer scheduledTimerWithTimeInterval:1.0
                                            target:self
                                          selector:@selector(updateTime)
                                          userInfo:nil
                                           repeats:YES];
    [time fire];
    [codeBtn setUserInteractionEnabled:NO];

    [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneNum.text zone:@"86" result:^(SMS_SDKError *error) {
        
        if (!error)
        {
            [USER_DEFAULT setObject:self.phoneNum.text forKey:@"registNum"];
            [USER_DEFAULT synchronize];
            [self.code becomeFirstResponder];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"验证码已经发送到您的手机上请输入验证码完成注册"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles: nil];
            [alert show];
        }
        else
        {
            UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"发送失败", nil)
                                                          message:[NSString stringWithFormat:@"状态码：%zi ,错误描述：%@",error.errorCode,error.errorDescription]
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                                otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
    
    
}

- (void)updateTime{
    
    [codeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",60 - count] forState:UIControlStateNormal];
    count ++;
    if (count == 61) {
        [codeBtn setUserInteractionEnabled:YES];
        [time invalidate];
        [codeBtn setTitle:[NSString stringWithFormat:@"点击获取验证码"]
                 forState:UIControlStateNormal];
    }
}

-(void)doRegister{

    if(self.code.text.length!=4)
    {
        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                      message:@"验证码格式错误,请重新填写"
                                                     delegate:self
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        //[[SMS_SDK sharedInstance] commitVerifyCode:self.verifyCodeField.text];
        [SMS_SDK commitVerifyCode:self.code.text result:^(enum SMS_ResponseState state) {
            if (1==state)
            {
                if ([self.titleStr isEqualToString:@"忘记密码"]) {
                    ResetWordViewController *reset = [[ResetWordViewController alloc]init];
                    reset.phoneNum = self.phoneNum.text;
                    [self.navigationController pushViewController:reset animated:YES];
                    return;
                }
                UserInfoViewController *userInfo  = [[ UserInfoViewController alloc]init];
                [self.navigationController pushViewController:userInfo animated:YES];
              
            }
            else if(0==state)
            {
                NSLog(@"验证失败");
                NSString* str=[NSString stringWithFormat:NSLocalizedString(@"验证码无效 请重新获取验证码", nil)];
                UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"验证码无效 请重新获取验证码", nil)
                                                              message:str
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                                    otherButtonTitles:nil, nil];
                [alert show];
            }
        }];
    }

   
}


-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
